const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const User = require('../models/User');
const router = express.Router();

// 配置文件上传
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../../storage/avatars');
    try {
      await fs.mkdir(uploadPath, { recursive: true });
      cb(null, uploadPath);
    } catch (error) {
      cb(error);
    }
  },
  filename: (req, file, cb) => {
    const uniqueName = `avatar_${Date.now()}_${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'));
    }
  }
});

/**
 * 获取用户信息
 */
router.get('/:phone', async (req, res) => {
  try {
    const { phone } = req.params;
    const user = await User.findByPhone(phone);
    
    if (!user) {
      return res.status(404).json({
        code: '40400',
        message: '用户不存在',
        data: null
      });
    }
    
    res.json({
      code: '20000',
      message: '获取用户信息成功',
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar_url: user.avatar_url,
        custom_avatar: user.custom_avatar,
        city: user.city,
        province: user.province,
        created_at: user.created_at,
        updated_at: user.updated_at
      }
    });
    
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      code: '50000',
      message: '获取用户信息失败',
      data: null
    });
  }
});

/**
 * 上传用户头像
 */
router.post('/:phone/avatar', upload.single('avatar'), async (req, res) => {
  try {
    const { phone } = req.params;
    
    if (!req.file) {
      return res.status(400).json({
        code: '40000',
        message: '请选择要上传的头像文件',
        data: null
      });
    }
    
    const user = await User.findByPhone(phone);
    if (!user) {
      return res.status(404).json({
        code: '40400',
        message: '用户不存在',
        data: null
      });
    }
    
    const avatarPath = `/storage/avatars/${req.file.filename}`;
    const success = await User.updateCustomAvatar(phone, avatarPath);
    
    if (!success) {
      return res.status(500).json({
        code: '50000',
        message: '头像上传失败',
        data: null
      });
    }
    
    res.json({
      code: '20000',
      message: '头像上传成功',
      data: {
        avatar_path: avatarPath,
        file_size: req.file.size,
        original_name: req.file.originalname
      }
    });
    
  } catch (error) {
    console.error('头像上传失败:', error);
    res.status(500).json({
      code: '50000',
      message: '头像上传失败',
      data: null
    });
  }
});

/**
 * 更新用户信息
 */
router.put('/:phone', async (req, res) => {
  try {
    const { phone } = req.params;
    const updateData = req.body;
    
    const user = await User.findByPhone(phone);
    if (!user) {
      return res.status(404).json({
        code: '40400',
        message: '用户不存在',
        data: null
      });
    }
    
    const userData = {
      phone,
      token: updateData.token || user.token,
      refresh_token: updateData.refresh_token || user.refresh_token,
      nickname: updateData.nickname || user.nickname,
      avatar_url: updateData.avatar_url || user.avatar_url,
      city: updateData.city || user.city,
      province: updateData.province || user.province,
      latitude: updateData.latitude || user.latitude,
      longitude: updateData.longitude || user.longitude
    };
    
    const result = await User.upsert(userData);
    
    res.json({
      code: '20000',
      message: '用户信息更新成功',
      data: {
        userId: result.userId,
        action: result.action
      }
    });
    
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      code: '50000',
      message: '更新用户信息失败',
      data: null
    });
  }
});

module.exports = router;
